package summary;

import java.util.*;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/7 22:02
 * https://leetcode-cn.com/problems/sort-characters-by-frequency/
 */
public class Title451 {

    public String frequencySort(String s) {
        Map<Character, Integer> hash = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            hash.put(s.charAt(i), hash.getOrDefault(s.charAt(i), 0) + 1);
        }
        Set<Map.Entry<Character, Integer>> entries = hash.entrySet();
        PriorityQueue<Map.Entry<Character, Integer>> priorityQueue = new PriorityQueue<>((a, b) -> (b.getValue().compareTo(a.getValue())));
        for (Map.Entry<Character, Integer> entry : entries) {
            priorityQueue.offer(entry);
        }
        StringBuilder result = new StringBuilder();
        while (!priorityQueue.isEmpty()) {
            Map.Entry<Character, Integer> poll = priorityQueue.poll();
            Integer value = poll.getValue();
            while (value-- > 0) {
                result.append(poll.getKey());
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {

    }
}
